import {ElMessage} from "element-plus";
import dayjs from "dayjs";


// ElementMsg提示
const msgLg = (message, type) => {
  ElMessage(
      type
          ? {
            type,
            message,
          }
          : message
  );
};
const msg = (message) => msgLg(message);
const msgSuccess = (message) => msgLg(message, "success");
const msgWarning = (message) => msgLg(message, "warning");
const msgError = (message) => msgLg(message, "error");

// 重置筛选内容
const reset = (params) => {
  const keys = Object.keys(params);
  let obj = {};
  keys.forEach((item) => {
    if (item === "pageNo") obj[item] = 1;
    else if (item === "pageSize") obj[item] = 10;
    else if (item === "createTime") obj[item] = [];
    else obj[item] = undefined;
  });
  return obj;
};

// 静态资源地址
const url =
    "http://weina-official-website.oss-cn-shanghai.aliyuncs.com/uploadFiles/products/";
const ossUrl = "https://weina-oms.oss-cn-shanghai.aliyuncs.com/";

// 防抖
let debounceTImer = null;
const debounce = (fun, delay = 500) => {
  return () => {
    if (debounceTImer) {
      clearTimeout(debounceTImer);
      debounceTImer = null;
    }
    debounceTImer = setTimeout(() => {
      fun();
    }, delay);
  };
};

// 节流
let timer = null;

function throttle(fn, delay = 300) {
  if (timer == null) {
    timer = setTimeout(() => {
      fn();
      clearTimeout(timer);
      timer = null;
    }, delay);
  }
}

// 禁选当日以及以前的时间
const disabledDate = (current) => {
  return current && current < dayjs().endOf("day");
};

/**
 * 格式化金额,每三位之间用逗号分割
 * @param {金额} num
 * @returns
 */
function toThousands(num) {
  if (typeof num === "number" && num >= 0) {
    return num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, "$1,");
  } else return "-";
}

/**
 * 根据上传的文件大小对比尺寸大小是否符合内容
 * @param {url地址} file
 * @param {尺寸大小} size
 * @returns
 */
const isUpImgSize = (file, size, look = false) => {
  return new Promise((resolve) => {
    let url = ossUrl + file;
    let img = new Image();
    img.src = url;
    img.onload = () => {
      if (`${size[0]}*${size[1]}` !== `${img.width}*${img.height}`) {
        if (look) {
          resolve("ok");
          msgWarning(
              `当前图片尺寸不符，请重新上传尺寸 ${size[0]}px * ${size[1]}px 图片`
          );
          return;
        }
        msgWarning(`图片尺寸不符，请传尺寸 ${size[0]}px * ${size[1]}px 图片`);
        return;
      }
      resolve(file);
    };
    img.onerror = () => {
      msgWarning(`图片获取失败，请重新上传`);
    };
  });
};

const tool = {
  msg,
  msgSuccess,
  msgWarning,
  msgError,
  reset,
  url,
  ossUrl,
  debounce,
  throttle,
  disabledDate,
  toThousands,
  isUpImgSize,
};

export default tool;
